package cms.com.yh.servlet;

import cms.common.Constant;
import cms.common.PageData;
import cms.common.Result;
import cms.mager.domain.User;
import cms.mager.service.UserService;
import cms.mager.service.impl.UserServiceImpl;
import cms.util.HttpCharSet;
import cms.util.InvokeHttp;
import cms.util.respUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能:
 * Author: yuhui
 * Date: 2021/4/8 17:29
 */
@MultipartConfig
public class Servlet_User extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpCharSet.charSet(req,resp);
        String service = req.getParameter("service");
        InvokeHttp.invokeReq(this,service,req,resp); // 请求分发接口
    }

    /**
     * 处理分页数据请求
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserService userService = new UserServiceImpl();
        //页码
        String page = req.getParameter("page");
        //每页数据条数
        String limit = req.getParameter("limit");
        PageData pd = new PageData();
        pd.setPage(Integer.valueOf(page));
        pd.setPageSize(Integer.valueOf(limit));
        //查询参数
        String realname = req.getParameter("realname");
        String role = req.getParameter("role");
        String deleted = req.getParameter("deleted");
        //用于存储查询参数
        Map<String,Object> param = new HashMap<>();
        if (StrUtil.isNotBlank(realname)){
            param.put("realname",realname);
        }
        if (StrUtil.isNotBlank(role)){
            param.put("role",role);
        }
        if (StrUtil.isNotBlank(deleted)){
            param.put("deleted",deleted);
        }
        Result rs = userService.findUserPage(pd.getPage(),pd.getPageSize(),pd);
        PrintWriter writer = resp.getWriter();
        //将数据转化为JSON消息
        String msg = JSONObject.toJSONString(rs);
        writer.print(msg);
        writer.flush();
        writer.close();
    }

    /**
     * 去user/list.jsp页面
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void userList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/view/user/list.jsp").forward(req,resp);
    }

    /**
    * 功能描述: 添加用户
    * @Author: yuhui  2021/4/9 17:09
    */
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String realname = req.getParameter("realname");
        Integer pwd = Integer.valueOf(req.getParameter("password"));
        Integer role = Integer.valueOf(req.getParameter("role"));

        Object[] objArr = {username,realname,pwd,role,new Date()};
        UserService uService = new UserServiceImpl();
        Result rt = uService.adduser(objArr);

        PrintWriter writer = resp.getWriter();
        writer.print(JSONObject.toJSONString(rt));
        writer.flush();
    }

    /**
    * 功能描述: 还原用户密码
    * @Author: yuhui  2021/4/9 19:11
    */
    public void resetPwd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        UserService u_service = new UserServiceImpl();
        Result result = u_service.reSetPwd(id, Constant.USER_DEFAULT_PASSWORD);
        PrintWriter writer = resp.getWriter();
        writer.print(JSONObject.toJSONString(result));
        writer.flush();
    }

    public void motifyPwd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //String oldpwd = req.getParameter("oldpwd");
        String newpwd = req.getParameter("newpwd");
        String id = req.getParameter("id");

        UserService userService = new UserServiceImpl();
        Result result = userService.updPwd(id, newpwd);
        respUtil.respOutPrint(result,resp);
    }

    /**
    * 功能描述: 删除用户
    * @Author: yuhui  2021/4/10 16:50
    */
    public void del(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));

        UserService us = new UserServiceImpl();
        Result result = us.delInfoById(id);
        PrintWriter writer = resp.getWriter();
        writer.print(JSONObject.toJSONString(result));
        writer.flush();
    }

    /**
    * 功能描述: 获取所有业务员姓名及ID
    * @Author: yuhui  2021/4/10 16:52
    */
    public void allName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        UserService us = new UserServiceImpl();
        Result allName = us.getAllName();
        respUtil.respOutPrint(allName,resp);
    }

    public void modifyImg(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        User user = (User)req.getSession().getAttribute("user");
        Part part = req.getPart("fileImg");
        String fileName = getFileName(part); //拿到文件名

        /*开始组装文件名，并持久化到硬盘*/
        String yyyyMMddHHssmmSSS = DateUtil.format(new Date(), "yyyyMMddHHssmmSSS");//使用Hutool的时间工具类
        String exst = FileUtil.extName(fileName); //获取大文件后缀
        String img = req.getServletContext().getRealPath("resources/img"); //获取项目的img文件夹真是路径
        String imgFile = yyyyMMddHHssmmSSS + "." + exst;
        String filePath = img + File.separator + imgFile;
        part.write(filePath); //将图片持久化到磁盘

        /*开始操作数据库*/
        UserService uc = new UserServiceImpl();
        Result result = uc.updImg("resources/img/"+imgFile, user.getId());
        respUtil.respOutPrint(result,resp);
    }

    /*获取上传的图片名称[ 带后缀 ]*/
    private String getFileName(Part part){
        String header = part.getHeader("Content-Disposition");
        String[] split = header.split(";");
        String[] FileNames = split[2].split("=");
        String fileName = FileNames[FileNames.length - 1];
        return fileName.substring(0,fileName.length()-1);
    }
}
